
import java.util.*;

public class UpdateHandler {
	
	private DB _db = null;							// program DB
	private EntryManager _entryManager = null; 		// reference to EntryManager object
	private ISocket _socket = null;					// active socket
	private PictureManager _pictureManager = null;	// reference to PictureManager object
	
	/**
	 * Constructor
	 * @param db
	 * @param entry
	 * @param socket
	 * @param pictureManager
	 */
	public UpdateHandler(DB db, EntryManager entry, ISocket socket, PictureManager pictureManager) {
		_db = db;
		_entryManager = entry;
		_socket = socket;
		_pictureManager = pictureManager;
	}
	
	/**
	 * Handles incoming "update" message.
	 * @param message
	 */
	public void handle(Message message) {
		String strData = new String(message.getData());
		String[] fields = Utils.parseMessage(strData); 
		
		String time = fields[0];
		String name = fields[1];
		
		// update SessionsManager with peer connection details
		SessionsManager.setSocket(name, new Source(_socket, message.getAddress(),message.getPort()));
		
		// set peer as Online and reset its connection tries counter to zero
		_db.setPeerOnline(name);
		
		// check if Picture Manager is handling this peer
		Record record = _pictureManager.isProcessingPeer(name);
		
		if (record == null)
			record = _db.getRecord(name);
		Date conn = new Date(System.currentTimeMillis());
		Date peerDate = Utils.StringToDate(time);
		
		if (record == null) {//No such peer exists
			//Add new peer 
			Record newRecord = new Record(name);
			newRecord.set_lastConnectionTime(conn);
			_db.addRecord(name, newRecord);
			
			//Send requestEntry(0)
			_entryManager.requestUpdates(Utils.zeroDate(), peerDate, name);
			
		} else if (record.get_dbVersion().compareTo(peerDate) != 1) {
			// update last connection time
			_db.updateLastConnection(name, new Date(System.currentTimeMillis()));
			
			if (record.get_dbVersion().compareTo(peerDate) == -1) {
				//RequestEntry from DB version
				_entryManager.requestUpdates(record.get_dbVersion(), peerDate, name);
			}
				
		}
		// initialize EntryManager status
		_entryManager.status();
	}
}
